
package com.jf.cloud.distribution.service.impl;

import cn.hutool.core.lang.Snowflake;
import com.github.binarywang.wxpay.bean.merchanttransfer.TransferCreateRequest;
import com.github.binarywang.wxpay.bean.merchanttransfer.TransferCreateResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.jf.cloud.api.platform.config.FeignShopConfig;
import com.jf.cloud.common.bean.WxApp;
import com.jf.cloud.common.database.dto.PageDTO;
import com.jf.cloud.common.database.util.PageUtil;
import com.jf.cloud.common.database.vo.PageVO;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.rocketmq.config.RocketMqConstant;
import com.jf.cloud.distribution.config.WxConfig;
import com.jf.cloud.distribution.mapper.EnterprisePayMapper;
import com.jf.cloud.distribution.model.EnterprisePay;
import com.jf.cloud.distribution.service.DistributionWithdrawCashService;
import com.jf.cloud.distribution.service.EnterprisePayService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.sound.sampled.LineUnavailableException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 商家转账
 *
 * @author zz
 * @date 2023-02-22 15:58:50
 */
@Service
public class EnterprisePayServiceImpl implements EnterprisePayService {

    @Autowired
    private EnterprisePayMapper enterprisePayMapper;

    @Autowired
    private FeignShopConfig feignShopConfig;

    @Autowired
    private WxConfig wxConfig;

    @Autowired
    private DistributionWithdrawCashService distributionWithdrawCashService;

    @Override
    public PageVO<EnterprisePay> page(PageDTO pageDTO) {
        return PageUtil.doPage(pageDTO, () -> enterprisePayMapper.list());
    }

    @Override
    public EnterprisePay getByEntPayId(Long entPayId) {
        return enterprisePayMapper.getByEntPayId(entPayId);
    }

    @Override
    public void save(EnterprisePay enterprisePay) {
        enterprisePayMapper.save(enterprisePay);
    }

    @Override
    public void update(EnterprisePay enterprisePay) {
        enterprisePayMapper.update(enterprisePay);
    }

    @Override
    public void deleteById(Long entPayId) {
        enterprisePayMapper.deleteById(entPayId);
    }

    @Override
    public List<EnterprisePay> listApplyEnterprisePay() {
        return enterprisePayMapper.listApplyEnterprisePay();
    }

    @Override
    public void sendEnterprisePay(List<EnterprisePay> enterprisePayList) {
        if (CollectionUtils.isEmpty(enterprisePayList)) {
            return;
        }
        String outBatchNo = new Snowflake().nextIdStr();
        TransferCreateRequest transferCreateRequest = new TransferCreateRequest();
        WxApp wxApp = feignShopConfig.getWxApp();
        transferCreateRequest.setAppid(wxApp.getAppId());
        transferCreateRequest.setOutBatchNo(outBatchNo);
        transferCreateRequest.setBatchName("NO_CHECK");
        transferCreateRequest.setBatchRemark("yami.cash.grant");
        List<TransferCreateRequest.TransferDetailList> transferDetailList = new ArrayList<>();
        int totalAmount = 0;
        for (EnterprisePay enterprisePay : enterprisePayList) {
            TransferCreateRequest.TransferDetailList transferDetail = new TransferCreateRequest.TransferDetailList();
            transferDetail.setOpenid(enterprisePay.getOpenId());
            transferDetail.setOutDetailNo(String.valueOf(enterprisePay.getEntPayOrderNo()));
            int amout = Integer.parseInt(enterprisePay.getAmount().toString());
            transferDetail.setTransferAmount(amout);
            transferDetailList.add(transferDetail);
            totalAmount += amout;
        }
        transferCreateRequest.setTotalAmount(totalAmount);
        transferCreateRequest.setTotalNum(enterprisePayList.size());
        transferCreateRequest.setTransferDetailList(transferDetailList);
        try {
            TransferCreateResult transfer = wxConfig.getMerchantTransferService().createTransfer(transferCreateRequest);
            enterprisePayList.forEach(enterprisePay -> {
                enterprisePay.setOutBatchNo(transfer.getOutBatchNo());
                //enterprisePay.setBatchId(transfer.getBatchId());
            });
            updateBatch(enterprisePayList);
        } catch (WxPayException wxPayException) {
            wxPayException.printStackTrace();
        }
    }

    @Override
    public void sendEnterprisePay(EnterprisePay enterprisePay) {
        if (Objects.isNull(enterprisePay)) {
            return;
        }
        TransferCreateRequest transferCreateRequest = new TransferCreateRequest();
        WxApp wxApp = feignShopConfig.getWxApp();
        transferCreateRequest.setAppid(wxApp.getAppId());
        transferCreateRequest.setOutBatchNo(enterprisePay.getOutBatchNo());
        transferCreateRequest.setBatchName("NO_CHECK");
        transferCreateRequest.setBatchRemark("yami.cash.grant");
        List<TransferCreateRequest.TransferDetailList> transferDetailList = new ArrayList<>();
        TransferCreateRequest.TransferDetailList transferDetail = new TransferCreateRequest.TransferDetailList();
        transferDetail.setOpenid(enterprisePay.getOpenId());
        transferDetail.setOutDetailNo(String.valueOf(enterprisePay.getEntPayOrderNo()));
        int amout = Integer.parseInt(enterprisePay.getAmount().toString());
        transferDetail.setTransferAmount(amout);
        transferDetailList.add(transferDetail);
        transferCreateRequest.setTotalAmount(amout);
        transferCreateRequest.setTotalNum(1);
        transferCreateRequest.setTransferDetailList(transferDetailList);
        try {
            wxConfig.getMerchantTransferService().createTransfer(transferCreateRequest);
        } catch (WxPayException wxPayException) {
            wxPayException.printStackTrace();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void paySuccess(EnterprisePay enterprisePay) {
        //更新商家转账信息
        if (enterprisePayMapper.paySuccess(enterprisePay.getEntPayOrderNo(), enterprisePay.getVersion()) != 1) {
            // 更新余额记录失败，请稍后再试
            throw new LuckException("更新余额记录失败，请稍后再试");
        }
        // 推送支付成功事件
        distributionWithdrawCashService.distributionWithdrawToSuccess(enterprisePay);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void payFailed(EnterprisePay enterprisePay) {
        //更新商家转账信息
        if (enterprisePayMapper.payFailed(enterprisePay.getEntPayOrderNo(), enterprisePay.getVersion()) != 1) {
            // 更新余额记录失败，请稍后再试
            throw new LuckException("更新余额记录失败，请稍后再试");
        }
        // 推送支付失败事件
        distributionWithdrawCashService.distributionWithdrawToFailed(enterprisePay);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBatch(List<EnterprisePay> enterprisePayList) {
        enterprisePayMapper.updateBatch(enterprisePayList);
    }

    @Override
    public List<EnterprisePay> listEnterprisePay() {
        return enterprisePayMapper.listEnterprisePay();
    }
}
